# coding: utf-8-sig

import sys
import os
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.spreadsheets.data
import gdata.spreadsheet.text_db
import codecs
import re

def get_sheet_key(client, book_name):
    m = re.search('http[s]*://', book_name)
    if (m is None):
        sheets = client.GetSpreadsheetsFeed()
        tlist = map(lambda e: e.title.text + " "  + e.id.text.rsplit('/', 1)[1], sheets.entry)
        for tt in tlist:
            buf = tt.rsplit(' ', 1)[0]
            key = tt.rsplit(' ', 1)[1]
            if buf == book_name:
                print 'Succeeded! key=', key
                return key
    print 'book ', book_name, ' is not found!'
    return 0

argvs = sys.argv
argc = len(argvs)
print 'argc: ', argc
if (argc != 5):
    print "Usage: mvc_query.py user pass シート名 {クエリー文字列}"
    quit()

email = argvs[1]
password = argvs[2]
book_name = argvs[3]
qry = argvs[4]
print 'email: ', email
print 'sheet: ', book_name
print 'query: ', qry

worksheet_id = 'od6'

spr_client = gdata.spreadsheet.service.SpreadsheetsService()
spr_client.email = email
spr_client.password = password
spr_client.source = 'Example Spreadsheet Writing Application'
spr_client.ProgrammaticLogin()

q = gdata.spreadsheet.service.ListQuery()
q['title'] = 'item-2013-02'

m = re.search('http[s]*://', book_name)
if m is None:
    print 'open_sheet!'
    #spreadsheet_key = get_sheet_key(spr_client, book_name)
    q['title'] = book_name
    feed = spr_client.GetSpreadsheetsFeed(query=q)
    spread_id = feed.entry[0].id.text.rsplit('/',1)[1]
    print 'spread_id: ', spread_id
    feed =spr_client.GetWorksheetsFeed(spread_id)
    sheet_id = feed.entry[0].id.text.rsplit('/',1)[1]
    print 'sheet_id: ', sheet_id
else:
    # only parse key from URL
    # like https://docs.google.com/spreadsheet/ccc?key=0AoQxLOjCIn7jdGk3RXptMnRaUnVkMFFTUDlreUwwR0E&usp=sharing#gid=0
    param1 = book_name.split('=')[1]
    spread_id = param1.split('&')[0]
    sheet_id = 'od6'

print 'key is: ', spread_id

if qry is not None:
    q.sq = qry
    records = spr_client.GetListFeed(spread_id, sheet_id, query=q).entry
else:
    records = spr_client.GetListFeed(spread_id, sheet_id).entry

filename = "query_output.txt"

try:
    os.remove (filename)
except:
    print 'no files found.'

articles = []
rcnt = 0
with open(filename, 'w') as f:
    for entry in records:
        rcnt = rcnt + 1
        article = gdata.spreadsheet.text_db.Record(row_entry=entry)
        articles.append(article.content)
        d = article.content

        buffer = u"%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % ( d['date'], d['server'], d['area'], d['alter'], d['address'], d['x'], d['z'], d['price'], d['item'] )
        b2 = buffer.encode('utf_8')
        f.write( b2 )
        f.write( '\n' )

print 'done fetch: %s records.' % (rcnt)
